package com.fept.msgcore.msgserver.protocol.util.crypto;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Srma on 2/9/2017.
 */
public class MessageDigestUtil {
    private static final char[] HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public MessageDigestUtil() {
    }

    public static String MD5(String s) throws NoSuchAlgorithmException {
        return messageDigest(s, "MD5");
    }

    public static boolean validateMessageDigest(byte[] data, String algorithm, byte[] mac) throws NoSuchAlgorithmException {
        byte[] newMac = messageDigest(data, algorithm);
        if(newMac != null && mac != null && newMac.length == mac.length) {
            for(int i = 0; i < mac.length; ++i) {
                if(newMac[i] != mac[i]) {
                    return false;
                }
            }

            return true;
        } else {
            return false;
        }
    }

    public static byte[] messageDigest(byte[] data, String algorithm) throws NoSuchAlgorithmException {
        MessageDigest mdInst = MessageDigest.getInstance(algorithm);
        mdInst.update(data);
        byte[] md = mdInst.digest();
        return md;
    }

    public static String messageDigest(String s, String algorithm) throws NoSuchAlgorithmException {
        byte[] btInput = s.getBytes();
        byte[] md = messageDigest(btInput, algorithm);
        int j = md.length;
        char[] str = new char[j * 2];
        int k = 0;

        for(int i = 0; i < j; ++i) {
            byte byte0 = md[i];
            str[k++] = HEX_DIGITS[byte0 >>> 4 & 15];
            str[k++] = HEX_DIGITS[byte0 & 15];
        }

        return new String(str);
    }
}
